package com.zyf.connotation.fragment

import android.app.ActivityOptions
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.RotateAnimation
import android.widget.AbsListView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zyf.connotation.BaseFragment
import com.zyf.connotation.R
import com.zyf.connotation.bean.Connotation
import com.zyf.connotation.presenter.ConnotationPresenter
import com.zyf.connotation.ui.ConnotationInfoActivity
import com.zyf.connotation.utils.ShardUtil
import com.zyf.connotation.view_interface.IConnotationView
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
import kotlinx.android.synthetic.main.connotation_fragment.view.*
import kotlinx.android.synthetic.main.rec_item.view.*
import java.util.*

/**
 * 作者：Think
 * 创建于 2017/5/31 14:39
 */
class ConnotationFragment :BaseFragment(), IConnotationView {
    var swipe: SwipeRefreshLayout?=null
    var recycle:RecyclerView?= null
    var animationSet:AnimationSet? = null
    var float_btn: FloatingActionButton? =null
    var floatBthRefresh = false
    var mLayoutInflater:LayoutInflater? = null
    var connotationAdapter:ConnotationAdapter? = null
    var presenter: ConnotationPresenter = ConnotationPresenter(this)
    var allData: ArrayList<Connotation.Data> = ArrayList()
    private var record = 0
    override fun initView(inflater: LayoutInflater?, container: ViewGroup?): View? {
        return inflater?.inflate(R.layout.connotation_fragment,container,false)
    }

    override fun initFindViewById(view: View?) {
        mLayoutInflater = LayoutInflater.from(baseActivity)
        swipe = view?.swipe
        recycle = view?.recycle
        float_btn = view?.float_btn
        swipe?.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light)
        swipe?.setOnRefreshListener {
            netData(true)
        }
        recycle?.layoutManager = LinearLayoutManager(baseActivity)
        recycle?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                val layoutManager = recyclerView!!.layoutManager as LinearLayoutManager
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                //当前屏幕所看到的子项个数
                val visibleItemCount = layoutManager.childCount
                //当前RecyclerView的所有子项个数
                val totalItemCount = layoutManager.itemCount
                //RecyclerView的滑动状态
                when (newState) {
                    AbsListView.OnScrollListener.SCROLL_STATE_IDLE -> if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 ) {
                        netData(false)
                    }
                }
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
        animationSet = AnimationSet(true)
        var rotate = RotateAnimation(0f,360f, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f)
        rotate.duration = 1000
        rotate.repeatCount = -1
        animationSet?.addAnimation(rotate)
        float_btn?.setOnClickListener {
            if(!floatBthRefresh){
                swipe?.setProgressViewOffset(false, 0, 48)
                swipe?.isRefreshing = true
                recycle?.scrollToPosition(0)
                netData(true)
            }
        }
        var data = ShardUtil.getPreferenceString(activity,"connotation")
        if(!TextUtils.isEmpty(data)){
            allData.addAll(Gson().fromJson<ArrayList<Connotation.Data>>(data,object:TypeToken<ArrayList<Connotation.Data>>(){}.type))
        }else{
            swipe?.setProgressViewOffset(false, 0, 48)
            swipe?.isRefreshing = true
        }
        connotationAdapter = ConnotationAdapter()
        recycle?.adapter = connotationAdapter
    }
    fun netData(isTop:Boolean){
        floatBthRefresh = true
        float_btn?.startAnimation(animationSet)
        presenter.getDataList(Connotation::class.java,isTop)
    }
    private fun initData(data:Connotation,istop: Boolean) {
        Toast.makeText(baseActivity,data.tip, Toast.LENGTH_SHORT).show()
        if(istop&&allData.size>100){
            var size = allData.size
            for(i in 0..20){
               allData.removeAt((size/2+10)-i)
            }
        }
        var i = 0
        data.data.forEach {
            if(it.type!=5){

                if(istop){
                    i++
                    allData.add(0,it)
                }else{
                    allData.add(it)
                }
            }
        }
        record = i
        connotationAdapter?.notifyDataSetChanged()
    }
    override fun initData() {
        if(allData.size!=0){
            return
        }
        presenter.getDataList(Connotation::class.java,true)
    }
    override fun <T> DataList(t: T?,isTop:Boolean) {
        swipe?.isRefreshing = false
        floatBthRefresh = false
        float_btn?.clearAnimation()
        initData(t as Connotation,isTop)
    }

    override fun fabulous(position: Int, check: String) {
        connotationAdapter?.notifyItemChanged(position)
    }

    inner class ConnotationAdapter:RecyclerView.Adapter<ConnotationHolder>(){
        override fun getItemCount(): Int {
            return allData.size
        }

        override fun onBindViewHolder(holder:ConnotationHolder, position: Int) {
            var data = allData[position]
            if(data.group.is_anonymous!=null&&data.group.is_anonymous){
                holder.anonymous?.visibility = View.VISIBLE
                holder.user_layout?.visibility = View.GONE
            }else{
                holder.anonymous?.visibility = View.GONE
                holder.user_layout?.visibility = View.VISIBLE
                holder.username?.text = data.group.user.name
                holder.head_img?.setImageURI(data.group.user.avatar_url)
            }
            if(record>0&&record-position == 1){
                holder.line?.visibility = View.GONE
            }else{
                holder.line?.visibility = View.VISIBLE
            }
            if( record>0&&record == position){
                //TODO
                holder.record_ll?.visibility = View.VISIBLE
                holder.record_ll?.setOnClickListener {
                    swipe?.setProgressViewOffset(false, 0, 48)
                    swipe?.isRefreshing = true
                    recycle?.scrollToPosition(0)
                    netData(true)
                }
            }else{
                holder.record_ll?.visibility = View.GONE
            }
            if(data.group.is_neihan_hot) holder.hot?.visibility = View.VISIBLE else holder.hot?.visibility = View.INVISIBLE

            holder.content?.text = data.group.content
            holder.category_name?.text = data.group.category_name
            holder.fabulous?.text = ""+data.group.digg_count
            if(data.group.user_digg == 1){
                holder.fabulous_image?.setImageResource(R.drawable.fabulous)
                holder.fabulous?.setTextColor(resources.getColor(R.color.textColor))
            }else{
                holder.fabulous_image?.setImageResource(R.drawable.no_fabulous)
                holder.fabulous?.setTextColor(resources.getColor(R.color.noColor))
            }
            holder.stampede?.text = ""+data.group.bury_count
            if(data.group.user_bury == 1){
                holder.stampede_image?.setImageResource(R.drawable.stampede)
                holder.stampede?.setTextColor(resources.getColor(R.color.textColor))
            }else{
                holder.stampede_image?.setImageResource(R.drawable.no_stampede)
                holder.stampede?.setTextColor(resources.getColor(R.color.noColor))
            }
            if(!TextUtils.isEmpty(data.group.mp4_url)){
                holder.videoplayer?.setUp(data.group.mp4_url, JCVideoPlayerStandard.SCREEN_LAYOUT_LIST,"")
                Glide.with(baseActivity).load(data.group.large_cover.url_list[0].url).into(holder.videoplayer?.thumbImageView)
            }else{
                holder.videoplayer?.visibility = View.GONE
            }
            holder.message?.text = ""+data.group.comment_count
            holder.fabulous_layout?.setOnClickListener {
                if(data.group.user_digg ==1||data.group.user_bury ==1){
                    Toast.makeText(this@ConnotationFragment.baseActivity,"您已经顶过",Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                presenter.netFabulous(position,"digg",data)
            }
            holder.stampede_layout?.setOnClickListener {
                if(data.group.user_digg ==1||data.group.user_bury ==1){
                    Toast.makeText(this@ConnotationFragment.baseActivity,"您已经顶过",Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                presenter.netFabulous(position,"bury",data)
            }
            holder.view?.setOnClickListener {
                var intent = Intent(this@ConnotationFragment.baseActivity, ConnotationInfoActivity::class.java)
                intent.putExtra("data",data)
                if (android.os.Build.VERSION.SDK_INT > 20)
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this@ConnotationFragment.baseActivity,holder.view,"conntation").toBundle())
                else
                    startActivity(intent)
            }
            holder.view?.setOnLongClickListener {
                var cm = this@ConnotationFragment.baseActivity?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                cm.primaryClip = ClipData.newPlainText(null,data.group.content)
                Toast.makeText(this@ConnotationFragment.baseActivity,"复制成功,可以发给您的朋友了",Toast.LENGTH_SHORT).show()
                return@setOnLongClickListener true
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ConnotationHolder {
            return ConnotationHolder(mLayoutInflater?.inflate(R.layout.rec_item, parent, false))
        }
    }
    inner class ConnotationHolder(itemView: View?): RecyclerView.ViewHolder(itemView){
        var view = itemView
        var hot = itemView?.hot
        var head_img = itemView?.head_img
        var username = itemView?.name
        var content = itemView?.content
        var category_name = itemView?.category_name
        var user_layout = itemView?.user_layout
        var anonymous = itemView?.anonymous
        var fabulous_image = itemView?.fabulous_image
        var fabulous = itemView?.fabulous
        var stampede_image = itemView?.stampede_image
        var stampede = itemView?.stampede
        var message = itemView?.message
        var fabulous_layout = itemView?.fabulous_layout
        var stampede_layout = itemView?.stampede_layout
        var record_ll = itemView?.record_ll
        var videoplayer = itemView?.videoplayer
        var line = itemView?.line
    }
    override fun onPause() {
        super.onPause()
        JCVideoPlayer.releaseAllVideos()
    }

    override fun onDestroy() {
        ShardUtil.savePreferenceString(baseActivity!!,"connotation",Gson().toJson(allData))
        super.onDestroy()
    }

    override fun error(error: String) {
        Toast.makeText(this@ConnotationFragment.baseActivity,error,Toast.LENGTH_SHORT).show()
        swipe?.isRefreshing = false
        floatBthRefresh = false
        float_btn?.clearAnimation()
    }
}